﻿using System;
using System.Threading;
using System.Threading.Tasks;

#nullable disable
namespace BeetleX.XRPC.Awaiter
{
    public sealed class AwaiterItem
    {
        private TaskCompletionSource<RPCPacket> completionSource;
        private int mFree;

        public int ID { get; set; }

        public double TimeOut { get; set; }

        public Type[] ResultType { get; set; }

        public TaskCompletionSource<RPCPacket> Create(long expiredTime)
        {
            this.TimeOut = (double)expiredTime;
            this.completionSource = new TaskCompletionSource<RPCPacket>();
            return this.completionSource;
        }

        public bool Completed(RPCPacket data)
        {
            if (Interlocked.CompareExchange(ref this.mFree, 1, 0) != 0)
                return false;
            data.ResultType = this.ResultType;
            this.completionSource.TrySetResult(data);
            return true;
        }

        public RPCPacket Request { get; set; }

        public RPCPacket Response { get; set; }
    }
}
